const Service = require("egg").Service;

class FormTemplateService extends Service {
  // 获取模板列表
  async getFormList () {
    const { app } = this;
    try {
      return await app.model.FormTemplate.findAll({
        attributes: ["id", "formName", "formCode"],
        where: { delFlag: 0 },
      });
    } catch (err) {
      console.log(err);
      return null;
    }
  }


  async modifyForm ({ id, formName, formCode }) {
    const { app } = this;
    try {
      if (!id) {
        return await app.model.FormTemplate.create({
          formName,
          formCode,
        });
      } else {
        const exit = await app.model.FormTemplate.findByPk(id);
        if (!exit) {
          this.ctx.logger.debug(`根据${id}无法查询到模板`);
          throw new Error("无法查询到模板");
        }
        exit.update({ formName, formCode, });
        return true;
      }
    } catch (err) {
      console.log(err);
      return null;
    }
  }

  async saveFormTemplate ({ id, formName, formCode, formTemplate }) {
    const { app } = this;
    try {
      if (!id) {
        return await app.model.FormTemplate.create({
          formName,
          formCode,
          formTemplate,
        });
      } else {
        const exit = await app.model.FormTemplate.findByPk(id);
        if (!exit) {
          this.ctx.logger.debug(`根据${id}无法查询到模板`);
          throw new Error("无法查询到模板");
        }
        exit.update({ formTemplate });
        return true;
      }
    } catch (err) {
      console.log(err);
      return null;
    }
  }

  async editorFormTemplate (id) {
    const { app } = this;
    try {
      return await app.model.FormTemplate.findOne({
        where: { id },
        include: {
          model: app.model.FormData,
          as: "formdata",
        },
      });
    } catch (err) {
      console.log(err);
      return null;
    }
  }

  async deleteFormTemplate (id) {
    const { app } = this;
    try {
      const exit = await app.model.FormTemplate.findByPk(id);
      if (!exit) {
        this.ctx.logger.debug(`根据${id}无法查询到模板`);
        throw new Error("无法查询到模板");
      }
      exit.update({ delFlag: 1 });
      return true;
    } catch (err) {
      console.log(err);
      return null;
    }
  }
}

module.exports = FormTemplateService;
